#!/bin/bash

# 定义要安装的Go版本
GO_VERSION="1.24.2"

# 检测系统架构
ARCH=$(uname -m)
case $ARCH in
    x86_64)
        GO_ARCH="amd64"
        ;;
    aarch64)
        GO_ARCH="arm64"
        ;;
    armv6l|armv7l)
        GO_ARCH="armv6l"
        ;;
    *)
        echo "不支持的系统架构: $ARCH"
        exit 1
        ;;
esac

# 下载链接
GO_TAR="go${GO_VERSION}.linux-${GO_ARCH}.tar.gz"
GO_URL="https://dl.google.com/go/${GO_TAR}"

# 安装目录 (使用/usr/local需要root权限，安装到用户目录则不需要)
INSTALL_DIR="/usr/local"
# 如果希望不需要root权限，可以改为用户目录，如:
# INSTALL_DIR="$HOME/.local"

# 检查是否已安装Go
if command -v go &> /dev/null; then
    echo "已安装Go: $(go version)"
    read -p "是否继续安装? (y/n) " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 0
    fi
fi

# 检查是否有root权限（如果安装到/usr/local）
if [ "$INSTALL_DIR" = "/usr/local" ] && [ "$(id -u)" -ne 0 ]; then
    echo "请使用root权限运行此脚本 (sudo)"
    exit 1
fi

# 下载Go
echo "正在下载 Go ${GO_VERSION} (${GO_ARCH})..."
wget -q --show-progress "$GO_URL" -O "$GO_TAR"

# 检查下载是否成功
if [ $? -ne 0 ]; then
    echo "下载失败，请检查网络连接或版本号"
    exit 1
fi

# 移除旧版本
echo "正在移除旧版本..."
rm -rf "${INSTALL_DIR}/go"

# 解压到安装目录
echo "正在安装..."
tar -C "$INSTALL_DIR" -xzf "$GO_TAR"

# 设置环境变量
echo "配置环境变量到 ~/.bashrc ..."
GO_PATH="${INSTALL_DIR}/go/bin"
USER_GOPATH="$HOME/go"

# 添加到用户的.bashrc
if ! grep -q "$GO_PATH" "$HOME/.bashrc"; then
    echo "" >> "$HOME/.bashrc"
    echo "# Go 环境变量" >> "$HOME/.bashrc"
    echo "export PATH=\$PATH:$GO_PATH" >> "$HOME/.bashrc"
    echo "export GOPATH=$USER_GOPATH" >> "$HOME/.bashrc"
    echo "export PATH=\$PATH:\$GOPATH/bin" >> "$HOME/.bashrc"
    echo "环境变量已添加到 ~/.bashrc"
else
    echo "环境变量已存在于 ~/.bashrc 中"
fi

# 立即生效当前会话的环境变量
export PATH=$PATH:$GO_PATH
export GOPATH=$USER_GOPATH
export PATH=$PATH:$GOPATH/bin

# 创建GOPATH目录
mkdir -p "$GOPATH"

# 清理安装文件
rm -f "$GO_TAR"

# 验证安装
if command -v go &> /dev/null; then
    echo "Go 安装成功: $(go version)"
    echo "请运行 source ~/.bashrc 使环境变量在当前终端生效，或重启终端"
else
    echo "安装失败，请检查安装过程"
    exit 1
fi
